<template>
  <div class="divSize" style="margin-top: 10%">
    <el-form
      ref="examRuleFormRef"
      :model="examInfo"
      status-icon
      :rules="examRules"
      label-width="80px"
      label-position="right"
      :inline="true">
      <h1 style="font-size: 26px;text-align: center">
        预约考试<el-button style="margin-left: 10px" type="danger" size="small" @click="ResetExam"
          >重置</el-button
        >
      </h1>
      <br />
      <div style="margin-left: 35%; margin-bottom: 20%">
        <h1>请选择你的考试时间:</h1>
        <br />
        <el-form-item prop="examDate">
          <el-date-picker
            type="date"
            :disabled="examDisabled"
            v-model="examInfo.examDate"
            placeholder="请选择"
            @change="updateTimeRange"
            style="width: 350px"
            :disabled-date="examDisabledDateFun"
          /> </el-form-item
        ><br/>
        <el-form-item prop="examTime">
          <el-time-select
            :disabled="examDisabled"
            style="width: 350px"
            v-model="examInfo.examTime"
            :start="currentStartTime"
            step="00:10"
            :end="currentEndTime"
            placeholder="选择时间"
            format="HH:mm:ss" />
        </el-form-item>
        <el-form-item>
          <span style="font-size: 16px; color: #545c64">考试状态: &nbsp;&nbsp;</span>
          <span v-if="examInfo.examState === '未考试'" style="color: #e6a23c">{{
            examInfo.examState
          }}</span>
          <span v-if="examInfo.examState === '已考试'" style="color: #409eff">{{
            examInfo.examState
          }}</span>
          <span v-else-if="examInfo.examState === '未通过'" style="color: #f56c6c">{{
            examInfo.examState
          }}</span>
          <span v-else-if="examInfo.examState === '已通过'" style="color: #67c23a">{{
            examInfo.examState
          }}</span>
        </el-form-item><br />

        <el-form-item>
          <el-button type="warning" @click="cancer">{{ cancerButton }}</el-button>
          <span style="margin-left: 175px"></span>
          <el-button
            :disabled="examDisabled"
            type="primary"
            @click="submitExamForm(examRuleFormRef)"
            >预约考试</el-button
          >
        </el-form-item>
      </div>
    </el-form>
  </div>

<!--  <div ClassMembersManager="divSize" style="margin-top: 3%">-->
<!--    <el-form-->
<!--      ref="exemptRuleFormRef"-->
<!--      :model="exemptInfo"-->
<!--      status-icon-->
<!--      :rules="exemptRules"-->
<!--      label-width="80px"-->
<!--      label-position="right"-->
<!--      :inline="true"-->
<!--    >-->
<!--      <h1 style="font-size: 26px">-->
<!--        关于免试<el-button style="margin-left: 10px" type="danger" size="small" @click="ResetExem"-->
<!--          >重置</el-button-->
<!--        >-->
<!--      </h1>-->
<!--      <span style="font-size: 15px; color: #909399"-->
<!--        >说明：前端技术栈或后端有项目可展示者可申请免试（面试时需要展示作品、项目），申请免试后无需预约考试</span-->
<!--      ><br /><br />-->
<!--      <div style="margin-left: 5%">-->
<!--        <h1>申请免试理由</h1>-->
<!--        <el-form-item prop="exemReason">-->
<!--          <el-input-->
<!--            v-model="exemptInfo.exemReason"-->
<!--            maxlength="200"-->
<!--            placeholder="请填写免试理由"-->
<!--            show-word-limit-->
<!--            type="textarea"-->
<!--            resize="none"-->
<!--            rows="5"-->
<!--            style="width: 550px"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <h1>若免试申请通过，选择你的面试时间:</h1>-->
<!--        <el-form-item prop="exemDate">-->
<!--          <el-date-picker-->
<!--            v-model="exemptInfo.exemDate"-->
<!--            placeholder="请选择"-->
<!--            style="width: 230px"-->
<!--            :disabled-date="exemDisabledDateFun"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item prop="exemTime">-->
<!--          <el-select-->
<!--            style="width: 230px"-->
<!--            v-model="exemptInfo.exemTime"-->
<!--            placeholder="选择时间"-->
<!--            clearable-->
<!--            @visible-change="visibleChange"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="item in timeList"-->
<!--              :key="item.value"-->
<!--              :label="item.value"-->
<!--              :value="item.value"-->
<!--              :disabled="item.disable"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <span v-if="exemptInfo.exemState !== '合格' && exemptInfo.exemState !== '不合格'">-->
<!--            <span style="font-size: 16px; color: #545c64">申请状态: &nbsp;&nbsp;</span>-->
<!--            <span v-if="exemptInfo.exemState === '审核中'" style="color: #e6a23c">{{-->
<!--              exemptInfo.exemState-->
<!--            }}</span>-->
<!--            <span v-if="exemptInfo.exemState === '已通过'" style="color: #67c23a">{{-->
<!--              exemptInfo.exemState-->
<!--            }}</span>-->
<!--            <span v-else-if="exemptInfo.exemState === '未通过'" style="color: #f56c6c">{{-->
<!--              exemptInfo.exemState-->
<!--            }}</span>-->
<!--          </span>-->
<!--          <span v-if="exemptInfo.exemState === '合格' || exemptInfo.exemState === '不合格'">-->
<!--            <span style="font-size: 16px; color: #545c64">免试中面试状态：&nbsp;&nbsp;</span>-->
<!--            <span v-if="exemptInfo.exemState === '不合格'" style="color: #f56c6c">{{-->
<!--              exemptInfo.exemState-->
<!--            }}</span>-->
<!--            <span v-if="exemptInfo.exemState === '合格'" style="color: #67c23a">{{-->
<!--              exemptInfo.exemState-->
<!--            }}</span>-->
<!--            <span style="font-size: 16px; color: #545c64; margin-left: 40px"-->
<!--              >面试分数: &nbsp;&nbsp;</span-->
<!--            >-->
<!--            {{ exemptInfo.exemScore }}-->
<!--          </span> </el-form-item-->
<!--        ><br />-->

<!--        <el-form-item style="margin-left: 28%">-->
<!--          <el-button type="primary" @click="submitExemForm(exemptRuleFormRef)">申请免试</el-button>-->
<!--        </el-form-item>-->
<!--      </div>-->
<!--    </el-form>-->
<!--  </div>-->
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref ,watch} from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  clear,
  getExamInfo,
  saveExamInfo,
} from '@/apis/bookExam'
import { userStore } from '@/stores/user'
import { getUserInfo} from '@/apis/security/user'
import { listTime } from '@/apis/system/time'
const isclear=ref(true)
const userstore = userStore()
const examRuleFormRef = ref<FormInstance>()
const exemptRuleFormRef = ref<FormInstance>()
const examDisabled = ref(true)
const cancerButton = ref('编辑预约')
const timeList = ref([{ value: '', disable: '' }])
const examTime = ref([{
  startDate: '',
  endDate: '',
  startTime: '',
  endTime: ''
}])
const examInfo = ref({
  examId: '',
  examDate: '',
  examTime: '',
  examState: '',
  examScore: ''
})
const exemTime = ref({
  exemStartDate: '',
  exemEndDate: '',
  exemStartTime: '',
  exemEndTime: ''
})
const exemptInfo = ref({
  exemId: '',
  exemReason: '',
  exemDate: '',
  exemTime: '',
  exemState: '',
  exemScore: ''
})
const queryParams = ref({
  pageNum: 1,
  pageSize: 1000,
  eventType: '', // 修改这里，允许 eventType 为字符串或 null
  startDate: null,
  endDate: null,
  startTime: null,
  endTime: null
})
const currentStartTime = ref('23:59:59');
const currentEndTime = ref('00:00:00');
const updateTimeRange = () => {
  if(isclear.value){
    examInfo.value.examTime=''
  }
  isclear.value=true;
  const selectedDate = new Date(examInfo.value.examDate);
  selectedDate.setHours(0, 0, 0, 0); // 设置为当天的开始时间

  const timeRange = examTime.value.find(time => {
    let startDate = new Date(time.startDate);
    startDate.setHours(0, 0, 0, 0); // 设置为当天的开始时间

    const endDate = new Date(time.endDate);
    endDate.setHours(0, 0, 0, 0); // 设置为当天的开始时间
    return selectedDate >= startDate && selectedDate <= endDate;
  });

  if (timeRange) {
    currentStartTime.value = timeRange.startTime;
    currentEndTime.value = timeRange.endTime;
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String((now.getMinutes()+10)).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const nowStr = `${hours}:${minutes}:${seconds}`
    console.log(`${hours}:${minutes}:${seconds}`);
    if(now>new Date(examInfo.value.examDate)){
      currentStartTime.value=nowStr
    }
  } else {
    currentStartTime.value = '23:59:59';
    currentEndTime.value = '00:00:00';
  }
}

watch(() => examInfo.value.examDate, updateTimeRange);

const getStudentInfo = () => {
  getUserInfo().then((res) => {
    console.log('获取学生信息')
    if (res.data.code === 200) {
      console.log('获取成功')
      userstore.userInfo = res.data.data
    } else {
      console.log('获取失败')
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}

const getExam = () => {
  getExamInfo().then((res) => {
    console.log('获取预约考试信息')
    if (res.data.code === 200) {
      console.log('获取成功')
      isclear.value=false
      examInfo.value = res.data.data
      if (examInfo.value === null) {
        examInfo.value = {
          examId: '',
          examDate: '',
          examTime: '',
          examState: '',
          examScore: ''
        }
      }
      if (examInfo.value.examState != null && examInfo.value.examState != '') {
        if (examInfo.value.examState === '已通过') {
          ElMessageBox.alert('恭喜你通过考试，请尽快预约面试', '提示', {
            confirmButtonText: '确定',
            callback: () => {}
          })
        }
      }
    } else {
      console.log('获取失败')
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}

const getTime = () => {
  queryParams.value.eventType = String('考试')
  queryParams.value.pageSize = Number(1e9);
  listTime(queryParams.value).then((res) => {
    console.log('获取时间')
    if (res.data.code === 200) {
      console.log('成功')
      examTime.value = res.data.data.records
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}
onMounted(() => {
  examDisabled.value = true
  getExam()
  getTime()
  userstore.defaultUrl = '/BookExam'
})
const ResetExam = () => {
  ElMessageBox.alert('重置后将从后台清除该考试所有信息，包括分数与状态，请谨慎', '危险', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    showCancelButton: true,
    type: 'warning'
  })
    .then(() => {
      clear().then((res) => {
        if (res.data.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          getExam()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {})
}
const examRules = reactive<FormRules<typeof examInfo>>({
  examDate: [{ required: true, message: '请选择预约考试时间', trigger: 'blur' }],
  examTime: [{ required: true, message: '请选择预约考试时间', trigger: 'blur' }]
})
const cancer = () => {
  examDisabled.value = examDisabled.value === false
  if (cancerButton.value === '取消编辑') {
    if (examInfo.value.examId != null && examInfo.value.examId != '') {
      getExamInfo().then((res) => {
        isclear.value=false
        examInfo.value = res.data.data
      })
    } else {
      examInfo.value = {
        examId: '',
        examDate: '',
        examTime: '',
        examState: '',
        examScore: ''
      }
    }
  }
  cancerButton.value = examDisabled.value === false ? '取消编辑' : '编辑预约'
}

const submitExamForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (examInfo.value.examState != '未考试' && examInfo.value.examState != '') {
        ElMessage({ type: 'error', message: '考试已完成，无法再次预约考试' })
        return
      }
      isclear.value = false
      if (typeof examInfo.value.examDate != 'string')
        examInfo.value.examDate = Format(examInfo.value.examDate)
      examInfo.value.examState = '未考试'
      saveExamInfo(examInfo.value).then((res) => {
        if (res.data.code === 200) {
          examDisabled.value = true
          cancerButton.value = '编辑预约'
          ElMessage({ type: 'success', message: '预约成功' })
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    }
  })
}

function Format(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

const examDisabledDateFun = (date: Date) => {
  for (const time of examTime.value) {
    const startDate = new Date(time.startDate);
    const endDate = new Date(time.endDate);

    // 确保日期比较在同一时区进行
    const isSameDay = (d1: Date, d2: Date) =>
      d1.getFullYear() === d2.getFullYear() &&
      d1.getMonth() === d2.getMonth() &&
      d1.getDate() === d2.getDate();

    //检查 date 是否在 当前时间之后
    const currentDate = new Date();
    currentDate.setHours(0, 0, 0, 0);
    if (date < currentDate) {
      return true;
    }
    // 检查 date 是否在 startDate 和 endDate 之间
    if (isSameDay(date, startDate) || isSameDay(date, endDate) || (date > startDate && date < endDate)) {
      return false;
    }
  }
  return true;
}
</script>

<style>
.inputSize {
  width: 220px;
  height: 30px;
}
.divSize {
  margin: 15px;
}

.el-icon {
  margin-left: 8px;
  margin-right: 8px;
}
.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-left: 8px;
  margin-right: 6px;
}
</style>
